import os, sys
import asyncake
import socket
import errno
import time

class MyDispatcher (asyncake.dispatcher, asyncake.TimeoutMixin):
    def __init__(self, parent, conn, addr):
        self.server = parent
        self.conn = conn
        self.client_addr = addr
        
        self.wbuf = ''
        asyncake.dispatcher.__init__(self, conn)

        self.set_timeout(1)
        print 'MyDispatcher:', conn.fileno(), self.client_addr

    def handle_read(self):
        print 'read:',
        s = self.recv(4096)
        self.wbuf = s
        print s

    def handle_write(self):
        print 'write:', self.wbuf
        n = self.send(self.wbuf)
        if n > 0:
            self.wbuf = self.wbuf[n:]

    def handle_timeout(self):
        print time.time(), 'timeout...'
        self.wbuf += 'timeout\r\n'
        self.set_timeout()

    def handle_expt(self):
        print 'found exception...'

    def handle_close(self):
        print 'socket close'
        self.close()

    def writable(self):
        if len(self.wbuf) > 0:
            return True
        return False


class MyServer (asyncake.dispatcher):
    def handle_connect(self):
        print 'connect...'

    def handle_accept(self):
        conn, addr = self.accept()
        print 'accept:', conn, conn.fileno(), addr
        MyDispatcher(self, conn, addr)

    def handle_expt(self):
        print 'server exception ??'

    def handle_close(self):
        self.close()

    def writable(self):
        return False
    


def test():
    x = asyncake.AsynCake(asyncake.EPOLL)
    #x = asyncake.AsynCake(asyncake.KQUEUE)

    dis = MyServer()
    dis.create_socket(socket.AF_INET, socket.SOCK_STREAM)
    dis.set_reuse_addr()
    dis.bind(('127.0.0.1', 10000))
    dis.listen(32)

    x.loop()

if __name__ == '__main__':
    test()


